﻿using BootyBay.PrivateStoreApp.AgentServicesRef;
using BootyBay.PrivateStoreApp.Common;
using BootyBay.PrivateStoreApp.Data;
using BootyBay.PrivateStoreApp.DataModel;
using BootyBay.PrivateStoreApp.StoreServicesRef;
using BootyBay.PrivateStoreApp.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “项详细信息页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234232 上提供

namespace BootyBay.PrivateStoreApp
{
    /// <summary>
    /// 显示组内某一项的详细信息的页面。
    /// </summary>
    public sealed partial class ItemDetailPage : Page
    {
        private UserAppDataModel userAppDataModel = null;
        private DispatcherTimer refresh_timer = new DispatcherTimer();
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();
        private Button btn = new Button();

        /// <summary>
        /// NavigationHelper 在每页上用于协助导航和
        /// 进程生命期管理
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        /// <summary>
        /// 可将其更改为强类型视图模型。
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }
        private AppDetailPageVM pageViewModel;

        public AppDetailPageVM PageViewModel
        {
            get { return pageViewModel; }
        }

        public ItemDetailPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState -= navigationHelper_LoadState;
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.DefaultViewModel["applistCategoryVM"] = AppListPageVM.Instance;
            this.DefaultViewModel["appDetailPageVM"] = AppDetailPageVM.Instance;
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。  在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="sender">
        /// 事件的来源; 通常为 <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">事件数据，其中既提供在最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的导航参数，又提供
        /// 此页在以前会话期间保留的状态的
        /// 字典。 首次访问页面时，该状态将为 null。</param>
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            userAppDataModel = (UserAppDataModel)e.NavigationParameter;
            LoadInfo();
            if (userAppDataModel != null)
            {
                AppListPageVM.Instance.LoadAppData(userAppDataModel.AppView.Keywords, userAppDataModel, "");
            }
        }

        void CategoryAppData_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
        }

        #region 加载信息
        private async void LoadInfo()
        {
            bool isShow = false;
            try
            {
                await AppDetailPageVM.Instance.LoadAppData(userAppDataModel);
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                isShow = true;
            }
            if (isShow)
            {
                var messageDialog = new MessageDialog("请先启动AgentSvcClient服务！");
                await messageDialog.ShowAsync();
            }
            else
            {
                pageViewModel = AppDetailPageVM.Instance;
                //this.DataContext = AppDetailPageVM.Instance;

                refresh_timer.Interval = new TimeSpan(0, 0, 1);
                refresh_timer.Tick -= refresh_timer_Tick;
                refresh_timer.Tick += refresh_timer_Tick;
                refresh_timer.Start();
            }
        }

        async void refresh_timer_Tick(object sender, object e)
        {
            //按钮可用
            btn.IsEnabled = true;
            //获取当前应用最新数据
            await AppDetailPageVM.Instance.LoadAppData(pageViewModel.AppModel);
            AppLocalStatus appLocalStatus = await AppDetailPageVM.Instance.GetAppLocalStatus(pageViewModel.AppModel);
            //刷新安装按钮和状态信息的显/隐状态
            if (appLocalStatus == AppLocalStatus.Installed)//已经安装
            {
                AppDetailPageVM.Instance.IsActionRequired = true;
                hyperLink_install.Visibility = Visibility.Collapsed;
            }
            else if (appLocalStatus == AppLocalStatus.InStore)//未按装
            {
                AppDetailPageVM.Instance.IsActionRequired = true;
                hyperLink_install.Visibility = Visibility.Collapsed;
            }
            else if (appLocalStatus == AppLocalStatus.Processing && AppDetailPageVM.Instance.AppModel.OptType != AppOperationType.Uninstall)//正在安装
            {
                //向下载列表中添加下载项
                DownloadAppsPageVM.Instance.AddDownloadApps(pageViewModel);
                hyperLink_install.Content = "正在安装 " + pageViewModel.AppModel.AppView.ApplicationName + " ...";
                hyperLink_install.Visibility = Visibility.Visible;
            }
        }
        #endregion

        #region NavigationHelper 注册

        /// 此部分中提供的方法只是用于使
        /// NavigationHelper 可响应页面的导航方法。
        /// 
        /// 应将页面特有的逻辑放入用于
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// 和 <see cref="GridCS.Common.NavigationHelper.SaveState"/> 的事件处理程序中。
        /// 除了在会话期间保留的页面状态之外
        /// LoadState 方法中还提供导航参数。


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        #endregion

        #region 跳转到你的应用页
        private void btn_AppList_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(YourAppsPage));
        }
        #endregion

        #region 跳转到主页
        private void btn_Home_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(MainPage));

        }
        #endregion

        #region 安装应用
        private async void btn_Install_Click(object sender, RoutedEventArgs e)
        {
            btn = sender as Button;
            try
            {
                bool bo = await AppDetailPageVM.Instance.GetValidateUser();
                if (btn.Content.ToString() != "Run" && bo)
                {
                    //单击安装按钮后使其不可用
                    btn.IsEnabled = false;
                    //向下载列表中添加下载项
                    DownloadAppsPageVM.Instance.AddDownloadApps(pageViewModel);
                    //打开刷新应用状态计时器
                    if (!refresh_timer.IsEnabled)
                    {
                        refresh_timer.Start();
                    }
                }
            }
            catch (System.UnauthorizedAccessException)
            {
            }


        }
        #endregion

        #region 跳转到下载应用页面
        private void hyperLink_install_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(DownloadAppsPage));
        }
        #endregion

        #region 离开当前页面时停止刷新应用状态
        private void pageRoot_Unloaded(object sender, RoutedEventArgs e)
        {
            refresh_timer.Stop();
            //AppListPageVM.Instance.CategoryAppData.Clear();
        }
        #endregion

        #region 跳转到相关应用页面
        private void Hub_SectionHeaderClick(object sender, HubSectionHeaderClickEventArgs e)
        {
            if (e.Section.Header.ToString() == "相关应用")
            {
                AppDetailPageVM.Instance.RelateAppModel = userAppDataModel;
                this.Frame.Navigate(typeof(SearchResultsPage), "");
            }
        }
        #endregion

        #region 点击列表项转到详细页
        private void itemGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            UserAppDataModel items = (UserAppDataModel)e.ClickedItem;
            if (items.AppView.IsPublicApp)
            {
                if (items.AppView.PublisherDisplayName != "")
                {
                    AppListPageVM.Instance.OpenPublicAppDetailPage(items.AppView.Publisher);
                }
            }
            else
            {
                this.Frame.Navigate(typeof(ItemDetailPage), items);
            }
        }
        #endregion

    }
}